package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Gallant
 * @create 2020-07-10 14:29
 */
@Component // 让spring帮助我创建这个类的对象
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    // 根据用户名进行封装用户详情对象
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.itheima.pojo.User user = userService.findByUsername(username);
        if (user == null) {
            return null;
        }
        // 创建一个list集合用户存储当前用户的角色信息
        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            // 将角色信息存储到list集合中
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            // 然后通过角色获取权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                // 授权
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        // 封装用户详情
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return userDetails;
    }
}
